<?php
	namespace Pages;
	class Index implements Page {
		public function __construct(){
		}
		public function exec($data){
		}
		public function toXML(){
			$xml = new \DOMDocument();
			$xml->load('Pages/Index.xml');
			$this->addPosts($xml);
			$this->addUsers($xml);
			return $xml;
		}
		public function getXSL($format){
			$xml = new \DOMDocument();
			switch($format){
				case 'html':
					$xml->load('XSL/html/Index.xsl');
					break;
				case 'rss':
					$xml->load('XSL/rss/Index.xsl');
					break;
			}
			return $xml;
		}

		private function addUsers($xml){
			$m = \Model\Model::getInstance();
			$users = $m->getAllUsers();
			$xmlUsers = $xml->createElement('users');
			foreach($users as $user){
				$xmlUser = $xml->createElement('user');
				$xmlUser->appendChild($xml->createTextNode($user->pseudo));
				$xmlUser->setAttribute('id',$user->id);
				$xmlUsers->appendChild($xmlUser);
			}
			$xml->getElementsByTagName('site')->item(0)->appendChild($xmlUsers);
		}

		private function addPosts($xml){
			$m = \Model\Model::getInstance();
			$posts = $m->getAllPosts();
			$xmlPosts = $xml->createElement('posts');
			foreach($posts as $post){
				$xmlPost = $xml->createElement('post');
				$xmlPost->setAttribute('url','http://'.$_SERVER['SERVER_NAME'].'/Post-'.$post->id.'.html');
				$xmlPost->setAttribute('id',$post->id);
				$author = $xml->createElement('author');
				$author->setAttribute('id',$post->userId);
				$author->appendChild($xml->createTextNode($post->userPseudo));
				$xmlPost->appendChild($author);
				$message = $xml->createElement('message');
				$message->appendChild($xml->createTextNode($post->message));
				$xmlPost->appendChild($message);
				$date = $xml->createElement('date');
				$date->appendChild($xml->createTextNode($post->date));
				$xmlPost->appendChild($date);
				$xmlPosts->appendChild($xmlPost);
			}
			$xml->getElementsByTagName('site')->item(0)->appendChild($xmlPosts);
		}
	}
?>
